package yams.domain;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.*;

import javax.persistence.*;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;

/**
 * 产品数据实体
 * Created by Silence on 2016/11/3.
 */
@Entity
@Table(name = "T_PRODUCT", schema = AbstractEntity.DB_SCHEMA)
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@JsonIgnoreProperties({"house","skus"})
public class ProductEntity extends AbstractEntity {

    @ManyToOne(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY)
    @JoinColumn(name = "CATE_ID", referencedColumnName = "PK_ID")
    CategoryEntity category;

    @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @OrderBy(value = "rowNum DESC")
    Set<ProductDataEntity> data;

    @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @OrderBy(value = "modifiedDate DESC")
    Set<SkuEntity> skus;

    @Lob
    @Column(length=20971520)
    String uedit;

    String primaryImage;

    /**
     * 是否特征资产，如果是的话，可以按照数量去生成子资产
     */
    Boolean characteristic=false;

    /**
     * 资产数量
     */
    Integer quantity;

    public String getValue(String attrId) {
        if (this.getData() != null) {
            Optional<ProductDataEntity> oa = this.getData().stream().filter(new Predicate<ProductDataEntity>() {
                @Override
                public boolean test(ProductDataEntity a) {
                    return a.getAttribute().getId().equals(attrId);
                }
            }).findFirst();
            if (oa.isPresent())
                return oa.get().getAttrValue();
        }
        return null;
    }
}
